package com.example.testcourse3;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

public class GuessNumberServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        GuessGame game = (GuessGame) request.getSession().getAttribute("game");
        String userGuessString = request.getParameter("userGuess");

        if (userGuessString == null || userGuessString.equals("")) {
            response.sendRedirect(request.getContextPath() + "/guess");
            return;
        }

        int userGuess = Integer.parseInt(userGuessString);

        if (userGuess < 1 || userGuess > 100) {
            response.sendRedirect(request.getContextPath() + "/guess");
            return;
        }

        String result = game.checkGuess(userGuess);
        if (result.equals("正确")) {
            response.sendRedirect(request.getContextPath() + "/right");
            return;
        } else {
            request.setAttribute("result", result);
            RequestDispatcher view = request.getRequestDispatcher("/guess.jsp");
            view.forward(request, response);
        }
    }
}